package org.simplextensions.ui.view;

import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.ui.SwingApplicationWindow;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class TabbedPaneViewManager extends ViewManager<TabbedPanelViewRegion> {

	private final JPanel jPanel;
	private JTabbedPane tabbedPane;

	public TabbedPaneViewManager(IExtensionRegistry extensionRegistry, JPanel jPanel) {
		super(extensionRegistry);
		this.jPanel = jPanel;
	}

	public TabbedPaneViewManager(SwingApplicationWindow applicationWindow) {
		super(applicationWindow.getExtensionRegistry());
		this.jPanel = applicationWindow.getjPanel();
		this.jPanel.setLayout(new GridLayout(1, 1));

		tabbedPane = new JTabbedPane();
		jPanel.add(tabbedPane);

		tabbedPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				for (IView<TabbedPanelViewRegion> view : getViews()){
					if (view.getViewRegion().getClientArea() == tabbedPane.getSelectedComponent())
						activateView(view);
				}
			}
		});

	}

	@Override
	protected void activateViewRegion(TabbedPanelViewRegion viewRegion) {
		tabbedPane.setSelectedComponent(viewRegion.getClientArea());
	}

	@Override
	protected void removeViewRegion(TabbedPanelViewRegion viewRegion) {
		this.tabbedPane.remove(viewRegion.getClientArea());
	}

	@Override
	protected TabbedPanelViewRegion createViewRegion() {
		return new TabbedPanelViewRegion(new JPanel(false));
	}

}
